'use strict';

// 添加一个变量来控制是否应该渲染背景
let shouldRender = false;
// 添加一个变量来存储动画帧ID
let animationFrameId = null;
// 添加一个变量来存储事件监听器函数
let handleMouseMoveFunc = null;

// 初始化项目背景函数
export function initProjectBackground() {
  const canvas = document.getElementById('projectBackgroundCanvas');
  if (!canvas) return; // 如果canvas不存在则直接返回
  const ctx = canvas.getContext('2d');
  if (!ctx) return; // 如果上下文不存在则直接返回
  
  // 确保canvas有父元素（即只在项目页面中）
  if (!canvas.parentElement) return;

  // 设置粒子参数
  const particleCount = 300;  // 增加粒子数量
  const particles = [];
  
  // 鼠标位置
  let mouseX = canvas.width / 2;
  let mouseY = canvas.height / 2;
  let mouseMoved = false;
  let lastMouseMoveTime = Date.now();
  
  // 粒子类
  class Particle {
    constructor() {
      this.reset();
      this.y = Math.random() * canvas.height;
      this.opacity = Math.random();
      this.opacitySpeed = (Math.random() - 0.5) * 0.02;
      // 添加生命周期属性
      this.life = Math.random() * 1000 + 1000; // 粒子生命周期
      this.age = 0;
    }
    
    reset() {
      this.x = Math.random() * canvas.width;
      this.y = Math.random() * canvas.height;
      this.size = Math.random() * 3 + 1;
      this.speedX = (Math.random() - 0.5) * 2;
      this.speedY = (Math.random() - 0.5) * 2;
      // 使用单一颜色
      this.baseColor = '51, 51, 51';
      this.age = 0;
      // 随机透明度变化速度
      this.opacitySpeed = (Math.random() - 0.5) * 0.05;
    }
    
    update() {
      // 增加粒子年龄
      this.age++;
      
      // 计算距离鼠标的位置
      const dx = this.x - mouseX;
      const dy = this.y - mouseY;
      const distance = Math.sqrt(dx * dx + dy * dy);
      
      // 检查鼠标是否长时间未移动（超过2秒）
      const timeSinceLastMove = Date.now() - lastMouseMoveTime;
      const isMouseStationary = timeSinceLastMove > 2000;
      
      if (isMouseStationary) {
        // 鼠标长时间未移动，粒子形成球形分布
        if (distance > 50) { // 缩小影响范围
          // 向球心移动，增加聚拢速度
          const force = 0.1;
          this.speedX -= (dx / distance) * force;
          this.speedY -= (dy / distance) * force;
        } else {
          // 在球内保持随机运动
          this.speedX += (Math.random() - 0.5) * 0.5;
          this.speedY += (Math.random() - 0.5) * 0.5;
        }
      } else if (mouseMoved) {
        // 鼠标移动时，粒子围绕鼠标运动
        if (distance < 200) { // 增加影响范围
          // 计算引力，增强碰撞幅度
          const force = (200 - distance) / 200 * 0.5;
          this.speedX += (dx / distance) * force;
          this.speedY += (dy / distance) * force;
        }
      }
      
      // 添加随机扰动，使粒子始终保持动态
      this.speedX += (Math.random() - 0.5) * 0.2;
      this.speedY += (Math.random() - 0.5) * 0.2;
      
      // 更新位置
      this.x += this.speedX;
      this.y += this.speedY;
      
      // 添加摩擦力，但减小摩擦力使粒子保持运动
      this.speedX *= 0.98;
      this.speedY *= 0.98;
      
      // 更新透明度
      this.opacity += this.opacitySpeed;
      
      // 透明度边界处理
      if (this.opacity <= 0.05 || this.opacity >= 0.8) {
        this.opacitySpeed = -this.opacitySpeed;
      }
      
      // 基于年龄和随机概率重置粒子
      if (this.age > this.life || Math.random() < 0.005) {
        this.reset();
      }
      
      // 边界检查
      if (this.x > canvas.width || this.x < 0 || this.y > canvas.height || this.y < 0) {
        this.reset();
      }
    }
    
    draw() {
      ctx.fillStyle = `rgba(${this.baseColor}, ${this.opacity})`;
      ctx.beginPath();
      ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
      ctx.fill();
    }
  }
  
  // 设置画布大小
  function resizeCanvas() {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    
    // 更新鼠标初始位置到画布中心
    mouseX = canvas.width / 2;
    mouseY = canvas.height / 2;
  }
  
  // 绘制背景
  function drawBackground() {
    // 填充黑色背景
    ctx.fillStyle = '#000000';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
  }
  
  // 初始化粒子
  function initParticles() {
    for (let i = 0; i < particleCount; i++) {
      particles.push(new Particle());
    }
  }
  
  // 更新粒子
  function updateParticles() {
    for (let i = 0; i < particles.length; i++) {
      particles[i].update();
    }
  }
  
  // 绘制粒子
  function drawParticles() {
    for (let i = 0; i < particles.length; i++) {
      particles[i].draw();
    }
  }
  
  // 鼠标移动事件处理
  handleMouseMoveFunc = function(e) {
    const rect = canvas.getBoundingClientRect();
    mouseX = e.clientX - rect.left;
    mouseY = e.clientY - rect.top;
    mouseMoved = true;
    lastMouseMoveTime = Date.now();
  };
  
  // 鼠标静止检测
  function checkMouseStationary() {
    const timeSinceLastMove = Date.now() - lastMouseMoveTime;
    if (timeSinceLastMove > 2000 && mouseMoved) {
      mouseMoved = false;
    }
    if (shouldRender) {
      requestAnimationFrame(checkMouseStationary);
    }
  }
  
  // 动画循环
  function animate() {
    if (shouldRender) {
      drawBackground();
      updateParticles();
      drawParticles();
      animationFrameId = requestAnimationFrame(animate);
    }
  }
  
  // 初始化画布大小并开始动画
  function initAndStart() {
    resizeCanvas();
    initParticles();
    
    // 窗口大小变化时重新调整画布
    window.addEventListener('resize', resizeCanvas);
    
    // 只在需要时添加鼠标事件监听器
    if (handleMouseMoveFunc) {
      canvas.addEventListener('mousemove', handleMouseMoveFunc);
      canvas.addEventListener('mouseenter', handleMouseMoveFunc);
      canvas.addEventListener('mouseleave', () => {
        mouseMoved = false;
      });
    }
    
    // 启动动画和鼠标静止检测
    animate();
    checkMouseStationary();
  }
  
  // 执行初始化
  initAndStart();
}

// 添加启用背景渲染和鼠标监听的函数
export function enableProjectBackground() {
  // 检查canvas元素是否存在且在DOM中
  const canvas = document.getElementById('projectBackgroundCanvas');
  if (!canvas || !canvas.parentElement) return;
  
  shouldRender = true;
  
  // 如果动画帧ID不存在，则重新初始化
  if (!animationFrameId) {
    const ctx = canvas.getContext('2d');
    if (!ctx) return;
    
    // 重新初始化画布和粒子系统
    initProjectBackground();
  }
}

// 添加禁用背景渲染和鼠标监听的函数
export function disableProjectBackground() {
  // 检查canvas元素是否存在
  const canvas = document.getElementById('projectBackgroundCanvas');
  if (!canvas) return;
  
  shouldRender = false;
  if (animationFrameId) {
    cancelAnimationFrame(animationFrameId);
    animationFrameId = null;
  }
}